package com.pervasa.demo.re.impl.data;

import java.util.Calendar;

public class TimeWindow {

	private boolean isNil;
	private boolean isRecur;
	private Calendar[] times = new Calendar[2];
	
	private static final int RECUR_YEAR = 2000;
	private static final int RECUR_MONTH = 1;
	private static final int RECUR_DAY = 1;
	
	public TimeWindow(Calendar calendar1, Calendar calendar2, boolean isRecur) {
		this.times[0] = calendar1;
		this.times[1] = calendar2;
		this.isNil = false;
		this.isRecur = isRecur;
		if (isRecur) {
			for (int i = 0; i != 2; ++i) {
				times[i].set(RECUR_YEAR, RECUR_MONTH, RECUR_DAY, times[i].get(Calendar.HOUR), times[i].get(Calendar.MINUTE), times[i].get(Calendar.SECOND));
			}
		}
	}
	
	public TimeWindow() {
		this.isNil = true;
		this.isRecur = false;
	}
	
	public boolean isActive() {
		if (isNil)
			return true;
		
		Calendar now = Calendar.getInstance();
		if (isRecur) {
			now.set(RECUR_YEAR, RECUR_MONTH, RECUR_DAY, now.get(Calendar.HOUR), now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
		}
		
		if (now.compareTo(times[0]) >= 0 && now.compareTo(times[1]) <= 0) {
			return true;
		}
		else return false;
	}
	
	public String toString() {
		if (isNil) {
			return "nil";
		}
		else if (isRecur) {
			return times[0].get(Calendar.HOUR) + ":" + times[0].get(Calendar.MINUTE) + ":" + times[0].get(Calendar.SECOND) + "-" +
			times[1].get(Calendar.HOUR) + ":" + times[1].get(Calendar.MINUTE) + ":" + times[1].get(Calendar.SECOND);
		}
		else {
			return times[0].get(Calendar.YEAR) + "/" + times[0].get(Calendar.MONTH) + "/" + times[0].get(Calendar.DAY_OF_MONTH) + "/" + times[0].get(Calendar.HOUR_OF_DAY) + ":" + times[0].get(Calendar.MINUTE) + ":" + times[0].get(Calendar.SECOND) + "-" +
			times[1].get(Calendar.YEAR) + "/" + times[1].get(Calendar.MONTH) + "/" + times[1].get(Calendar.DAY_OF_MONTH) + "/" + times[1].get(Calendar.HOUR_OF_DAY) + ":" + times[1].get(Calendar.MINUTE) + ":" + times[1].get(Calendar.SECOND);
		}
	}
	
	public long getDelay() {
		return times[1].getTimeInMillis() - times[0].getTimeInMillis();
	}
}
